#include <stack>
#include <vector>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode new_head(0);
        new_head.next = head;
        ListNode* node1 = &new_head;
        ListNode* node2 = node1->next;
        while (node2 != nullptr) {
            stack<ListNode*> stack;
            for (int i = 0; i < k && node2 != nullptr; i++) {
                stack.push(node2);
                node2 = node2->next;
            }
            if (stack.size() == k) {
                while (!stack.empty()) {
                    node1->next = stack.top();
                    stack.pop();
                    node1 = node1->next;
                }
            }
            if (node2 == nullptr) {
                if (!stack.empty()) {
                    while (stack.size() > 1) {
                        stack.pop();
                    }
                    node1->next = stack.top();
                } else {
                    node1->next = nullptr;
                }
                break;
            }
        }
        return new_head.next;
    }
};

int main() {
    ListNode l1(1), l2(2), l3(3), l4(4), l5(5);
    l1.next = &l2;
    //l2.next = &l3;
    //l3.next = &l4;
    //l4.next = &l5;
    Solution solution;
    solution.reverseKGroup(&l1, 2);
}

